<script setup lang="ts">
import { h, onMounted, ref } from 'vue';
import {
  NButton,
  NCard,
  NDataTable,
  NEmpty,
  NForm,
  NFormItem,
  NInput,
  NList,
  NListItem,
  NModal,
  NPopconfirm,
  NSelect,
  NSpace,
  NTag,
  NThing,
  useMessage
} from 'naive-ui';
import type { DataTableColumns } from 'naive-ui';

// 定义用户类型
interface User {
  id: string;
  username: string;
  email: string;
  role: string;
  status: 'active' | 'inactive';
  createdAt: string;
}

// 消息提示
const message = useMessage();

// 表格数据
const users = ref<User[]>([]);
const loading = ref(false);

// 分页相关
const pagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 30]
});

// 模态框相关
const showModal = ref(false);
const isEditing = ref(false);
const currentUser = ref<Partial<User>>({});

// 角色选项
const roleOptions = [
  { label: '管理员', value: 'admin' },
  { label: '普通用户', value: 'user' },
  { label: '访客', value: 'guest' }
];

// 状态选项
const statusOptions = [
  { label: '激活', value: 'active' },
  { label: '禁用', value: 'inactive' }
];

// 编辑用户
const handleEdit = (user: User) => {
  isEditing.value = true;
  currentUser.value = { ...user };
  showModal.value = true;
};

// 删除用户
const handleDelete = (id: string) => {
  users.value = users.value.filter(user => user.id !== id);
  message.success('删除成功');
};

// 保存用户
const handleSave = () => {
  if (!currentUser.value.username) {
    message.warning('请输入用户名');
    return;
  }

  if (!currentUser.value.email) {
    message.warning('请输入邮箱');
    return;
  }

  if (isEditing.value) {
    // 编辑用户
    const index = users.value.findIndex(user => user.id === currentUser.value.id);
    if (index !== -1) {
      users.value[index] = { ...users.value[index], ...currentUser.value } as User;
      message.success('更新成功');
    }
  } else {
    // 新增用户
    const newUser: User = {
      id: Date.now().toString(),
      username: currentUser.value.username!,
      email: currentUser.value.email!,
      role: currentUser.value.role || 'user',
      status: currentUser.value.status || 'active',
      createdAt: new Date().toISOString().split('T')[0]
    };
    users.value.unshift(newUser);
    message.success('新增成功');
  }

  showModal.value = false;
};

// 获取角色标签
const getRoleLabel = (role: string) => {
  const roleOption = roleOptions.find(item => item.value === role);
  return roleOption?.label || role;
};

// 获取状态标签
const getStatusTag = (status: 'active' | 'inactive') => {
  return h(
    NTag,
    { type: status === 'active' ? 'success' : 'error', size: 'small' },
    { default: () => (status === 'active' ? '激活' : '禁用') }
  );
};

// 表格列定义
const createColumns = (): DataTableColumns<User> => {
  return [
    {
      title: '用户名',
      key: 'username'
    },
    {
      title: '邮箱',
      key: 'email'
    },
    {
      title: '角色',
      key: 'role',
      render(row) {
        const role = roleOptions.find(item => item.value === row.role);
        return role?.label || row.role;
      }
    },
    {
      title: '状态',
      key: 'status',
      render(row) {
        return h(
          NTag,
          { type: row.status === 'active' ? 'success' : 'error' },
          { default: () => (row.status === 'active' ? '激活' : '禁用') }
        );
      }
    },
    {
      title: '创建时间',
      key: 'createdAt'
    },
    {
      title: '操作',
      key: 'actions',
      render(row) {
        return h(NSpace, null, {
          default: () => [
            h(
              NButton,
              {
                size: 'small',
                onClick: () => handleEdit(row)
              },
              { default: () => '编辑' }
            ),
            h(
              NPopconfirm,
              {
                onPositiveClick: () => handleDelete(row.id)
              },
              {
                default: () => '确认删除该用户吗？',
                trigger: () =>
                  h(
                    NButton,
                    {
                      size: 'small',
                      type: 'error',
                      quaternary: true
                    },
                    { default: () => '删除' }
                  )
              }
            )
          ]
        });
      }
    }
  ];
};

const columns = createColumns();

// 获取用户数据
const fetchUsers = async () => {
  loading.value = true;
  try {
    // 模拟 API 调用
    // 实际项目中应该调用真实的 API
    await new Promise(resolve => {
      setTimeout(resolve, 500);
    });

    // 模拟数据
    users.value = [
      {
        id: '1',
        username: 'admin',
        email: 'admin@example.com',
        role: 'admin',
        status: 'active',
        createdAt: '2023-01-01'
      },
      {
        id: '2',
        username: 'user1',
        email: 'user1@example.com',
        role: 'user',
        status: 'active',
        createdAt: '2023-02-01'
      },
      {
        id: '3',
        username: 'user2',
        email: 'user2@example.com',
        role: 'user',
        status: 'inactive',
        createdAt: '2023-03-01'
      },
      {
        id: '4',
        username: 'user3',
        email: 'user3@example.com',
        role: 'user',
        status: 'active',
        createdAt: '2023-04-01'
      },
      {
        id: '5',
        username: 'user4',
        email: 'user4@example.com',
        role: 'guest',
        status: 'inactive',
        createdAt: '2023-05-01'
      }
    ];

    pagination.value.itemCount = users.value.length;
  } catch {
    message.error('获取用户数据失败');
  } finally {
    loading.value = false;
  }
};

// 处理分页变化
const handlePageChange = (page: number) => {
  pagination.value.page = page;
  fetchUsers();
};

// 处理页面大小变化
const handlePageSizeChange = (pageSize: number) => {
  pagination.value.pageSize = pageSize;
  pagination.value.page = 1;
  fetchUsers();
};

// 新增用户
const handleAdd = () => {
  isEditing.value = false;
  currentUser.value = {};
  showModal.value = true;
};

// 组件挂载时获取数据
onMounted(() => {
  fetchUsers();
});
</script>

<template>
  <div class="user-management">
    <NCard title="用户管理">
      <template #header-extra>
        <NButton type="primary" @click="handleAdd">新增用户</NButton>
      </template>

      <!-- 响应式内容区域 -->
      <div class="content-container">
        <!-- 桌面端表格视图 -->
        <div class="desktop-view">
          <NDataTable
            :columns="columns"
            :data="users"
            :loading="loading"
            :pagination="pagination"
            remote
            @update:page="handlePageChange"
            @update:page-size="handlePageSizeChange"
          />
        </div>

        <!-- 移动端卡片视图 -->
        <div class="mobile-view">
          <NList v-if="users.length > 0" class="mobile-list">
            <NListItem v-for="user in users" :key="user.id">
              <NThing>
                <template #header>
                  <span class="user-name">{{ user.username }}</span>
                </template>
                <template #header-extra>
                  <NSpace>
                    <NButton size="tiny" @click="handleEdit(user)">编辑</NButton>
                    <NPopconfirm @positive-click="handleDelete(user.id)">
                      <template #trigger>
                        <NButton size="tiny" type="error" quaternary>删除</NButton>
                      </template>
                      确认删除该用户吗？
                    </NPopconfirm>
                  </NSpace>
                </template>

                <div class="user-info-grid">
                  <div class="user-info-item">
                    <div class="user-info-label">邮箱:</div>
                    <div class="user-info-value">{{ user.email }}</div>
                  </div>
                  <div class="user-info-item">
                    <div class="user-info-label">角色:</div>
                    <div class="user-info-value">{{ getRoleLabel(user.role) }}</div>
                  </div>
                  <div class="user-info-item">
                    <div class="user-info-label">状态:</div>
                    <div class="user-info-value">
                      <component :is="getStatusTag(user.status)" />
                    </div>
                  </div>
                  <div class="user-info-item">
                    <div class="user-info-label">创建时间:</div>
                    <div class="user-info-value">{{ user.createdAt }}</div>
                  </div>
                </div>
              </NThing>
            </NListItem>
          </NList>

          <!-- 空状态 -->
          <NEmpty v-else description="暂无用户数据" />
        </div>
      </div>
    </NCard>

    <!-- 用户编辑/新增模态框 -->
    <NModal v-model:show="showModal" preset="card" class="user-modal" title="用户信息">
      <NForm :model="currentUser" label-placement="left" label-width="80">
        <NFormItem label="用户名" path="username">
          <NInput v-model:value="currentUser.username" placeholder="请输入用户名" />
        </NFormItem>

        <NFormItem label="邮箱" path="email">
          <NInput v-model:value="currentUser.email" placeholder="请输入邮箱" />
        </NFormItem>

        <NFormItem label="角色" path="role">
          <NSelect v-model:value="currentUser.role" :options="roleOptions" placeholder="请选择角色" />
        </NFormItem>

        <NFormItem label="状态" path="status">
          <NSelect v-model:value="currentUser.status" :options="statusOptions" placeholder="请选择状态" />
        </NFormItem>
      </NForm>

      <template #footer>
        <NSpace justify="end">
          <NButton @click="showModal = false">取消</NButton>
          <NButton type="primary" @click="handleSave">保存</NButton>
        </NSpace>
      </template>
    </NModal>
  </div>
</template>

<style scoped>
.user-management {
  padding: 16px;
}

.n-card {
  margin-bottom: 16px;
}

.content-container {
  width: 100%;
}

/* 桌面端视图 - 默认显示 */
.desktop-view {
  display: block;
}

.mobile-view {
  display: none;
}

.user-info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
  margin-top: 8px;
}

.user-info-item {
  display: flex;
  flex-direction: column;
}

.user-info-label {
  font-size: 12px;
  color: #999;
}

.user-info-value {
  font-size: 14px;
  margin-top: 2px;
}

.user-modal {
  width: 90%;
  max-width: 500px;
}

.user-name {
  font-weight: bold;
}

/* 移动端适配 - 当屏幕宽度小于等于768px时 */
@media (max-width: 768px) {
  .desktop-view {
    display: none;
  }

  .mobile-view {
    display: block;
  }

  .user-info-grid {
    grid-template-columns: 1fr;
  }

  .user-management {
    padding: 8px;
  }

  /* 移动端卡片样式优化 */
  :deep(.n-list-item) {
    padding: 12px 0;
    border-bottom: 1px solid var(--n-border-color);
  }

  :deep(.n-list-item:last-child) {
    border-bottom: none;
  }

  :deep(.n-thing-main__) {
    padding: 0;
  }
}
</style>
